package com.cictec.middleware.gps.engine.position.handler.alarms;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cictec.middleware.commons.utils.Constants;
import com.cictec.middleware.commons.utils.DateUtils;
import com.cictec.middleware.commons.utils.PMSUtils;
import com.cictec.middleware.commons.utils.PropertiesUtils;
import com.cictec.middleware.core.entity.BusLineStation;
import com.cictec.middleware.core.entity.WarnMsg;
import com.cictec.middleware.gps.engine.BusInstance;
import com.cictec.middleware.gps.engine.TimingPoint;
import com.cictec.middleware.gps.engine.exception.BusPositionWarnHandlerException;
import com.cictec.middleware.gps.engine.position.handler.BusPositionAlarmsHandler;
import com.cictec.middleware.gps.service.BusLineService;
import com.cictec.middleware.gps.service.WarnMsgService;


/**
 * 站点停车时间过短（甩站报警）
 * @author ql
 * @date 2017年9月26日
 */
@Component
public class StationStopTooShortWarnHandler implements WarnHandler{

	private static Logger logger = LoggerFactory.getLogger(BusPositionAlarmsHandler.class);

	@Autowired
	private WarnMsgService warnMsgService;
	@Autowired
	private BusLineService busLineService;
	
	/** 甩站的时间阈值 单位秒，过站时间小于该阈值，认为甩站。*/
	private static int dumpStation = 12;
	
	@Override
	public String getWarnType() {
		return Constants.VAL_BUS_STATUS_13;
	}
	
	@Override
	public void onHandler(BusInstance busInstance) throws BusPositionWarnHandlerException {
		logger.debug("【甩站报警信息处理】");
		
		if(isStopWarn(busInstance)){
			// 停止上一次甩站报警
			stopWarn(busInstance);
		}
		
		if(!busInstance.isEnterOut()){
			return;
		}
		

		
		TimingPoint preStation = busInstance.getPreStation();
		TimingPoint currentStation = busInstance.getCurrentStation();
		
		if(currentStation != null && preStation != null){
			dumpStation = PropertiesUtils.getIntValue("system.parameter.warn.dumpStation", dumpStation);
			String preSeq = preStation.getStationLineSeqOrg();
			String currentSeq = currentStation.getStationLineSeqOrg();
			
//			System.out.println(preStation.getStationLineSeqOrg() + "\t"+preStation.getStationEnterOut() + "\t" + preStation.getGatherTime());
//			System.out.println(currentStation.getStationLineSeqOrg() + "\t"+currentStation.getStationEnterOut() + "\t" + currentStation.getGatherTime());
			if(preSeq.equals(currentSeq)){
				// 站内甩站判定
				if(preStation.isInStation() && !busInstance.isInStation()){
					long secondsInterval = DateUtils.secondInterval(currentStation.getTime(), preStation.getTime());
					// 可以在此打断点观察 时间差
					if(currentStation.getTime().getTime() > preStation.getTime().getTime() 
							&& secondsInterval < dumpStation){
						
						startWarn(busInstance, null);
					}
				}
				
			}else{
				// 站间甩站，至判断站序递增情况
				int cSeq = Integer.parseInt(currentSeq);
				int pSeq = Integer.parseInt(preSeq);
				int seqInterval = cSeq - pSeq;
				if(seqInterval > 1){
					// 站间甩站
					for (int i = 1; i < seqInterval; i++) {
						// 新增站间甩站，目前不实线，业务没做强制要求
						BusLineStation station = busLineService.getLineStationByStationSeq(currentStation.getLineUuid(), currentStation.getStationLineTypeOrg(), cSeq + 1);
						startWarn(busInstance, station);
					}
				}
			}
		}
		
	}

	public void startWarn(BusInstance busInstance, BusLineStation ls) {
		
		BusLineStation station = null;

		if(ls == null){
			TimingPoint point = busInstance.getCurrentStation();
			station = busLineService.getLineStationByStationSeq(point.getLineUuid(), point.getStationLineTypeOrg(), point.getStationLineSeqOrg());
		}else{
			station = ls;
		}
		
		// 在站时间超过压站的阈值，判定为压站。
		WarnMsg warnMsg = new WarnMsg();
		warnMsg.setWarnBusUuid(busInstance.getBusUuid());
		warnMsg.setWarnDevUuid(busInstance.getDevUuid());
		warnMsg.setWarnDrvUuid(busInstance.getDriverUuid());

		warnMsg.setWarnLineUuid(busInstance.getLineUuid());
		warnMsg.setWarnType(Constants.VAL_BUS_STATUS_13);
		warnMsg.setWarnStartLat(busInstance.getLatitude());
		warnMsg.setWarnStartLng(busInstance.getLongitude());
		warnMsg.setWarnStartTime(DateUtils.formatDateTimes(busInstance.getTime()));

		warnMsg.setWarnStaUuid(station.getLsStaUuid());
		warnMsg.setWarnStorageTime(DateUtils.formatDateTimes(new Date()));
		// warnMsg.setWarnOperStatus(Constants.VAL_BUS_OPER_STATUS_1);
		warnMsg.setWarnOperStatus(busInstance.getStatusInOperateTime());

		warnMsgService.saveWarn(warnMsg);
		WarnMsg cWarnMsg = busInstance.getWarnsByWarnType(Constants.VAL_BUS_STATUS_13);
		if (cWarnMsg == null) {
			busInstance.setWarns(Constants.VAL_BUS_STATUS_13, warnMsg);
		} else {
			// 先停止之前的在 添加新的
			stopWarn(busInstance);
			busInstance.setWarns(Constants.VAL_BUS_STATUS_13, warnMsg);
		}
	}
	
	
	/**
	 * 甩站停止条件：<br>
	 * 
	 * 
	 * 非运营 <br>
	 * 偏线<br>
	 * 站内停留时间符合设定条件 <br>
	 * 不是最后一站 <br>
	 * 线路切换 <br>
	 * 不再站内 <br>
	 * 
	 * @param busInstance
	 * @return
	 */
	private boolean isStopWarn(BusInstance busInstance) {
		// 偏线、非运营、不再站内
		if (busInstance.isInDeviate() || !busInstance.isInOperateTime() || !busInstance.isInStation()) {
			// 如果是偏线，默认停止压站报警
			return true;
		}
		
		
		// 最后一站 
		if (busInstance.isEnterOut()) {
			TimingPoint currentStation = busInstance.getCurrentStation();
			boolean isLastStation = busLineService.isLastLineStation(busInstance.getLineUuid(), busInstance.getLineType(), currentStation.getStationLineSeqOrg());
			if (isLastStation) {
				return true;
			}
		}
		
		// 线路切换
		TimingPoint prePoint = busInstance.getTimingPoint(-1);
		if (!prePoint.getLineType().equals(busInstance.getLineType())) {
			return true;
		}
		
		return false;
	}
	
	@Override
	public void stopWarn(BusInstance busInstance) {
		WarnMsg warnMsg = busInstance.getWarnsByWarnType(Constants.VAL_BUS_STATUS_13);
		if (warnMsg != null) {

			warnMsg.setWarnEndLat(busInstance.getLatitude());
			warnMsg.setWarnEndLng(busInstance.getLongitude());
			warnMsg.setWarnEndTime(DateUtils.formatDateTimes(busInstance.getTime()));

			warnMsg.setWarnStorageTime(DateUtils.formatDateTimes(new Date()));
//			warnMsg.setWarnOperStatus(Constants.VAL_BUS_OPER_STATUS_1);
			warnMsg.setWarnOperStatus(busInstance.getStatusInOperateTime());
			warnMsg.setWarnDuration(PMSUtils.isNull(DateUtils.secondInterval(warnMsg.getWarnStartTime(), warnMsg.getWarnEndTime())));
			
			warnMsgService.saveWarn(warnMsg);

			busInstance.setWarns(Constants.VAL_BUS_STATUS_13, null);
		}
	}

}
